/************************************************/
/*				head.s by doom119				*/
/*					April, 2010					*/
/************************************************/

#now we are in 32-bit code, notice that we are still set cli

.text
.global _startup_32, _idt, _gdt, _pg_dir
#page directory at the address of 0x0
_pg_dir:
_startup_32:
	movl $0x10, %eax
	mov %ax, %ds
	mov %ax, %es
	mov %ax, %fs
	mov %ax, %gs

//set stack temporarly,must be modified
	mov %ax, %ss 

	call setup_idt
	call setup_gdt

#to reload cs
	ljmp $8, $go

go:
	movl $0x10, %eax
	mov %ax, %ds
	mov %ax, %es
	mov %ax, %fs
	mov %ax, %gs

//set stack temporarly,must be modified
	lss stack_start, %esp

#check whether A20 is enable
1:
	xorl %eax, %eax
	incl %eax
	movl %eax, 0x000000
	cmpl 0x000001, %eax
	je 1b

#set WP bit, and ignoring math coprocessor for simple
	movl %cr0, %eax
	orl  $0x10000, %eax
	movl %eax, %cr0

	jmp after_page_tables

#we don't load ignore_int for simple
setup_idt:
	lidt _idt_desc
	ret

setup_gdt:
	lgdt _gdt_desc
	ret

#reserve memory page tables, 4KB for every table
.org 0x1000
_pg0:
.org 0x2000
_pg1:
.org 0x3000
_pg2:
.org 0x4000
_pg3:

.org 0x5000
after_page_tables:
	pushl $0
	pushl $0
	pushl $0
	pushl $blunder
	pushl $main
	jmp paging
blunder:
	jmp blunder

.align 4
paging:
	movl $1024*5, %ecx
	xorl %eax, %eax
	xorl %edi, %edi
	rep
	stosl

	movl $_pg0+7, _pg_dir
	movl $_pg1+7, _pg_dir+4
	movl $_pg2+7, _pg_dir+8
	movl $_pg3+7, _pg_dir+12

	movl $_pg3+4092, %edi
	movl $0xFFF007, %eax
1:
	std
	stosl
	sub $0x1000, %eax
	jge 1b

	xorl %eax, %eax
	movl %eax, %cr3

	movl %cr0, %eax
	orl  $0x80000000, %eax
	movl %eax, %cr0
	ret

.align 4
.word 0
_idt_desc:
	.word 256*8-1
	.long _idt

.align 4
.word 0
_gdt_desc:
	.word 256*8-1
	.long _gdt

_idt:	.fill 256, 8, 0

_gdt:
	.quad 0x0
	.quad 0x00c09a0000000fff
	.quad 0x00c0920000000fff
	.fill 253, 8, 0

